import { CydonElement, define, watch } from 'cydon'
import { CPagination } from './CPagination'
import { DataFilter } from './DataFilter'
import { error } from '@cydon/ui/Message'
import './DataFilter'
import './CPagination'

const colBlacklist = new Set(['', '图片', '操作'])

/**
 * @element c-table
 * 分页表格
 */
@define('c-table')
export class CTable<T extends {} = {}> extends CydonElement {
	static observedAttributes = ['col-keys', 'col-names', 'per-pages']

	/** 数据 */
	items: T[] = []
	/** 分页器 */
	page!: CPagination
	/** 筛选器 */
	filter?: DataFilter

	/** 键名 */
	keys!: string[]
	/** 列名 */
	columns!: string[]

	/** 排序方向 */
	get sortDir() {
		const dir = this.filter?.sortKeys.find(({ index }) => index == this.k)?.dir
		return dir ? dir == 5 ? ' 随机' : (dir & 1 ? '↑' : '↓') : ''
	}

	k!: number

	connectedCallback() {
		super.connectedCallback()
		let f: DataFilter
		if (!this.filter)
			return
		// eslint-disable @typescript-eslint/no-this-alias
		const that = this
		that.filter!.keys = that.keys
		that.filter!.columns = that.columns.filter(x => !colBlacklist.has(x))
		// 监听筛选器变化
		watch(this.filter, function (this: DataFilter) {
			if (f)
				that.updateContents(that.page, f).catch(error)
			else
				f = this
		})
		watch(this.filter, function (this: DataFilter) {
			if (this.sortKeys)
				that.updateValue('filter')
		})
		// 监听分页器的页码变化
		watch(this.page, function (this: CPagination) {
			// 获取数据
			that.updateContents(this, f).catch(error)
		})
	}

	attributeChangedCallback(name: string, _oldVal: string, newVal: string) {
		if (name == 'col-keys')
			this.keys = newVal.split(',')
		if (name == 'col-names')
			this.columns = newVal.split(',')
		if (name == 'per-pages')
			queueMicrotask(() =>
				this.page.perPages = newVal.split(',').map(x => parseInt(x)))
	}

	/** 排序 */
	sortBy(index: number) {
		if (this.filter) {
			const { sortKeys } = this.filter
			const i = sortKeys.findIndex(({ index: i }) => i == index)
			if (sortKeys[i]?.dir) {
				if (sortKeys[i].dir == 2)
					sortKeys.splice(i, 1)
				else
					sortKeys[i].dir = 2
			} else
				sortKeys.push({ index, dir: 1 })
		}
	}

	/** 更新内容 */
	async updateContents(p: CPagination, f?: DataFilter) {
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'c-table': CTable
	}
}
